package org.jeecg.modules.middleware.rabbitmq.gen;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.middleware.rabbitmq.gen.EnumGenHandler;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class GenMqUtil {

    private static RabbitTemplate rtt;

    @Autowired
    public GenMqUtil(RabbitTemplate template) {
        template.setEncoding("UTF-8");
        //设置手工ack确认
        template.setMandatory(true);
        template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String s) {
                if (!ack) {
                    try {
                        String jsonData = new String(correlationData.getReturnedMessage().getBody(), "utf-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        template.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                try {
                    String jsonData = new String(message.getBody(), "utf-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        rtt = template;
    }

    public static void sendMsg(EnumGenHandler handler , String channel, Object msg){
        try {
            String handlerName = handler.getHandlerName();
            if (StringUtils.isEmpty(handlerName)) {
                return;
            }
            JSONObject jo = new JSONObject();
            jo.put("handlerName", handlerName);
            jo.put("channel", channel);
            jo.put("msg", msg);
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            rtt.convertAndSend("genExchange", "gen", jo.toJSONString(),
                    message -> {
                        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                        return message;
                    }
                    , correlationData);
        }catch (Exception e){

        }
    }


}
